<?php

namespace ticket\modules\backend\models;

use Yii;

/**
 * This is the model class for table "tk_ticket_categorys".
 *
 * @property int $cat_id
 * @property int $app_id
 * @property string $cat_name 名称
 * @property string $image_url 图片
 * @property int $cat_type '类型1-普通分类2-系统分类3-网店信息4-帮助分类5-网店帮助',
 * @property int $parent_id 父级Id
 * @property string $all_parent_id 所有fuid
 * @property int $child 子ID
 * @property string $all_child_id 所有子Id
 * @property string $link 外链
 * @property int $number 分类下的数量
 * @property int $hits 点击量
 * @property string $keywords 关键字
 * @property string $cat_desc 描述
 * @property int $sort 排序
 * @property string $show_in_nav 1-显示,2-隐藏
 */
class TicketCategorys extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'tk_ticket_categorys';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['app_id', 'required', 'message' => 'AppId不能为空','on' => ['addCategory']],
            ['cat_name', 'required', 'message' => '分类名称不能为空'],
            ['cat_name', 'string', 'max' => 30],
            ['image_url', 'string', 'max' => 255],
            ['cat_type', 'in', 'range' => [1, 2, 3, 4, 5], 'message' => '类型格式不正确'],
            ['parent_id', 'integer', 'message' => '父ID格式不正确'],
            ['link', 'string', 'max' => 100],
            ['keywords', 'string', 'max' => 255],
            ['cat_desc', 'string', 'max' => 255],
            ['sort', 'integer', 'message' => '排序格式不正确'],
            ['show_in_nav', 'in', 'range' => [2, 1], 'message' => '导航格式不正确'],
            [['hits', 'all_parent_id', 'child', 'all_child_id'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'cat_id' => 'Cat ID',
            'app_id' => 'App ID',
            'cat_name' => 'Cat Name',
            'image_url' => 'Image Url',
            'cat_type' => 'Cat Type',
            'parent_id' => 'Parent ID',
            'all_parent_id' => 'All Parent ID',
            'child' => 'Child',
            'all_child_id' => 'All Child ID',
            'link' => 'Link',
            'number' => 'Number',
            'hits' => 'Hits',
            'keywords' => 'Keywords',
            'cat_desc' => 'Cat Desc',
            'sort' => 'Sort',
            'show_in_nav' => 'Show In Nav',
        ];
    }


    public function addCategory($app_id,$data)
    {
        $data = [
            'TicketCategorys' =>  $data
        ];

        $this->scenario = 'addCategory';
        if  (!isset($data['TicketCategorys']['sort']) and empty($data['TicketCategorys']['sort'])){
            $data['TicketCategorys']['sort'] = 0;
        }
        $data['TicketCategorys']['app_id'] = $app_id;
        if (!empty($data['TicketCategorys']['image_url'])){
            $data['TicketCategorys']['image_url'] = json_encode($data['TicketCategorys']['image_url']);
        }else{
            $data['TicketCategorys']['image_url'] = '';
        }
        if ((int)$data['TicketCategorys']['parent_id'] === 0){ // 说明是顶级分类
            if($this->load($data) and $this->validate()){
                if($this->save(false)){
                    /*写入日志*/
                    return true;
                }
            }
            return false;
        }

        $category = self::find()->select(['cat_id','parent_id','all_parent_id','all_child_id'])->where('cat_id = :cid',[':cid' => $data['TicketCategorys']['parent_id']])->one();
        if (is_null($category)){
            $this->addError('parent_id','上级分类不存在');
            return false;
        }


        $data['TicketCategorys']['all_parent_id'] = $category->all_parent_id | $category->all_parent_id.','.$data['TicketCategorys']['parent_id']; // 增加all_parent_id
        if ($this->load($data) and $this->validate()){
            $transaction = Yii::$app->db->beginTransaction();
            try{
                $this->save(false);
                for ($i = 0; $i < count($allParentIdArr = explode(',',$this->all_parent_id));$i++){
                    if ($allParentIdArr[$i]){
                        $category = self::find()->select(['cat_id','parent_id','all_parent_id','all_child_id'])->where('cat_id = :cid',[':cid' => $allParentIdArr[$i]])->one();
                        $category->child = 1;
                        $category->all_child_id = ($category->all_child_id?$category->all_child_id. ',':'').$this->getPrimaryKey();
                        $category->save(false);
                    }
                }
                $transaction->commit();
                return true;
            }catch (Exception $e){
                $transaction->rollBack();
                return false;
            }
        }
    }



    public function modCategory($id, $data)
    {
        $data = [
            'TicketCategorys' =>  $data
        ];
        if (!empty($data['TicketCategorys']['image_url'])){
            $data['TicketCategorys']['image_url'] = json_encode($data['TicketCategorys']['image_url']);
        }else{
            $data['TicketCategorys']['image_url'] = '';
        }

        if($data['TicketCategorys']['parent_id']){//如果不是顶级分类，需要验证上级目录是否存在
            $parentCategory = self::find()->select('cat_id, parent_id, all_parent_id, all_child_id')->where('cat_id = :catid', [':catid' => $data['TicketCategorys']['parent_id']])->one();
            if(is_null($parentCategory)){
                $this->addError('parent_id', '上级分类不存在');
                return false;
            }
        }

        if ($this->load($data) and $this->validate()){
            $articleCategory = self::find()->where('cat_id = :catid', [':catid' => $id])->one();
            if(is_null($articleCategory)){
                return false;
            }
            if(($data['TicketCategorys']['parent_id'] == $articleCategory->cat_id) or (in_array($data['TicketCategorys']['parent_id'], explode(',', $articleCategory->all_child_id)))){//如果父级 选择的是自身，或者选择的是子级的话
                $this->addError('parent_id', '类别不能选择自身和子分类');
                return false;
            }
            $transaction = Yii::$app->db->beginTransaction();
            try{
                if ($articleCategory->parent_id === $data['TicketCategorys']['parent_id']){ // 没有修改分类
                    $articleCategory->cat_name = $data['TicketCategorys']['cat_name'];
                    $articleCategory->image_url = $data['TicketCategorys']['image_url'];
                    $articleCategory->parent_id = $data['TicketCategorys']['parent_id'];
                    $articleCategory->link = $data['TicketCategorys']['link'];
                    $articleCategory->sort = isset($data['TicketCategorys']['sort'])?$data['TicketCategorys']['sort']:0;
                    $articleCategory->keywords = isset($data['TicketCategorys']['keywords'])?$data['TicketCategorys']['keywords']:'';
                    $articleCategory->cat_desc = isset($data['TicketCategorys']['cat_desc'])?$data['TicketCategorys']['cat_desc']:"";
                    $articleCategory->show_in_nav = isset($data['TicketCategorys']['show_in_nav'])?$data['TicketCategorys']['show_in_nav']:"1";
                    $articleCategory->save(false);//修改文章分类
                }else{ // 修改了分类
                    for($i=0; $i<count($allParentIdArr = explode(',', $articleCategory->all_parent_id)); $i++){
                        if($allParentIdArr[$i]){
                            $category = self::find()->select('cat_id, all_parent_id, child, all_child_id')->where('cat_id = :catid', [':catid' => $allParentIdArr[$i]])->one();
                            $tmpArr = explode(',', $category->all_child_id);
                            foreach ($tmpArr as $k => $v){
                                if (($v == $articleCategory->cat_id) or (in_array($v, explode(',', $articleCategory->all_child_id)))){
                                    unset($tmpArr[$k]);
                                }
                            }
                            if(count($tmpArr)){
                                $category->child = 1;
                            }else{
                                $category->child = 0;
                            }
                            $category->all_child_id = implode(',', $tmpArr);
                            $category->save(false);
                        }
                    }


                    if($data['TicketCategorys']['parent_id'] > 0){//如果父级是顶级分类
                        $data['TicketCategorys']['all_parent_id'] = $parentCategory->all_parent_id|$parentCategory->all_parent_id . ',' . $data['TicketCategorys']['parent_id'];//整理自身的all_parent_id
                    }else{
                        $data['TicketCategorys']['all_parent_id'] = '0';//整理自身的all_parent_id
                    }
                    /*修改文章分类    B*/
                    $articleCategory->cat_name = $data['TicketCategorys']['cat_name'];
                    $articleCategory->image_url = $data['TicketCategorys']['image_url'];
                    $articleCategory->parent_id = $data['TicketCategorys']['parent_id'];
                    $articleCategory->all_parent_id = $data['TicketCategorys']['all_parent_id'];
                    $articleCategory->link = $data['TicketCategorys']['link'];
                    $articleCategory->sort = isset($data['TicketCategorys']['sort'])?$data['TicketCategorys']['sort']:0;
                    $articleCategory->keywords = isset($data['TicketCategorys']['keywords'])?$data['TicketCategorys']['keywords']:'';
                    $articleCategory->cat_desc = isset($data['TicketCategorys']['cat_desc'])?$data['TicketCategorys']['cat_desc']:"";
                    $articleCategory->show_in_nav = isset($data['TicketCategorys']['show_in_nav'])?$data['TicketCategorys']['show_in_nav']:"1";
                    $articleCategory->save(false);//修改文章分类
                    /*就是在所有父级 添加自身的cat_id 和子级的cat_id*/
                    for($i=0; $i<count($allParentIdArr = explode(',', $articleCategory->all_parent_id)); $i++){
                        if($allParentIdArr[$i]){
                            $category = self::find()->select('cat_id, all_parent_id, child, all_child_id')->where('cat_id = :catid', [':catid' => $allParentIdArr[$i]])->one();
                            $category->child = 1;
                            if($articleCategory->all_child_id){
                                $category->all_child_id = ($category->all_child_id?$category->all_child_id . ',':'') . $articleCategory->cat_id . ',' . $articleCategory->all_child_id;
                            }else{
                                $category->all_child_id = ($category->all_child_id?$category->all_child_id . ',':'') . $articleCategory->cat_id;
                            }
                            $category->save(false);
                        }
                    }

                    for($i=0; $i<count($allChildIdArr = explode(',', $articleCategory->all_child_id)); $i++){
                        if($allChildIdArr[$i]){
                            $category = self::find()->select('cat_id, all_parent_id, child, all_child_id')->where('cat_id = :catid', [':catid' => $allChildIdArr[$i]])->one();
                            $category->all_parent_id = $articleCategory->all_parent_id . ',' . $articleCategory->cat_id;
                            $category->save(false);
                        }
                    }
                }
                $transaction->commit();
                return true;
            }catch (Exception $e){
                $transaction->rollback();
                return false;
            }
            return false;
        }
    }




    public function delCategory($id,$app_id)
    {
        $articleCategory = $this::find()->where('cat_id = :id', [':id' => $id])->one();

        if ($app_id != $articleCategory->app_id || is_null($articleCategory)){
            return $this->addError('app_id', '参数有误,删除失败');
        }
        /*查看该分类下有没有子类*/
        if($articleCategory->child){
            $this->addError('cat_name', '此分类下含有子分类！');
            return false;
        }
        $ticketInfo = TicketInfo::find()->where('category = :cat_id',[':cat_id' => $id])->one();
        if  (!is_null($ticketInfo)){
            $this->addError('category', '此分类下含有门票！');
            return false;
        }

        $transaction = Yii::$app->db->beginTransaction();//事物处理
        try{
            /*修改所有上级目录的child字段和all_child_id字段(所有上级)>>>>*/
            for($i=0; $i<count($allParentIdArr = explode(',', $articleCategory->all_parent_id)); $i++){
                if($allParentIdArr[$i]){
                    $parent = self::find()->select('cat_id, all_parent_id, child, all_child_id')->where('cat_id = :catid', [':catid' => $allParentIdArr[$i]])->one();
                    // P($parent);
                    if($parent->all_child_id == $articleCategory->cat_id){//说明上级目录只有一个子目录了
                        $parent->child = 0;
                        $parent->all_child_id = '';
                        // P($parent);
                    }else{
                        $tmpArr = explode(',', $parent->all_child_id);
                        foreach($tmpArr as $k => $v){
                            if($tmpArr[$k] == $articleCategory->cat_id){
                                // P($tmpArr[$k] ."-". $articleCategory->cat_id);
                                // array_remove($tmpArr, $k);
                                unset($tmpArr[$k]);
                            }
                        }
                        $parent->all_child_id = implode(',', $tmpArr);
                    };
                    $parent->save(false);
                }
            }
            /*修改所有上级目录的child字段和all_child_id字段(所有上级)<<<<*/

            $articleCategory->delete();
            /*写入日志*/
            $transaction->commit();
            return true;
        }catch(\Exception $e){
            $transaction->rollback();
            throw new \Exception($e);
            return false;
        };
    }

    public static function getTreeList($cat_id = 0,$app_id)
    {
        $cat_id = (int)$cat_id;
        $articleList = self::find()->where(['like','all_parent_id',$cat_id])->andFilterWhere(['app_id' => $app_id])->orderBy(['sort' => SORT_DESC])->asArray()->all();
        $articleList = self::setTreeList($articleList,$cat_id);
        return $articleList;
    }


    /*
  递归函数
  返回一个 商品分类 树列表

  $arr        需要处理的数组
  $parent_id  从哪个分类
  */
    private static function setTreeList($arr, $parent_id)
    {
        static $list = array();
        static $level = 0;//层级
        $level++;

        $total = self::getNumById($arr, $parent_id);//此ID下有多少条数据
        $tmp = 0;//一共匹配到几个
        for($i=0; $i<count($arr); $i++){
            $arr[$i]["level"] = $level;
            if($arr[$i]["parent_id"] == $parent_id){
                $tmp++;//匹配到之后加1
                if($tmp == $total){
                    $end = 0;
                }else{
                    $end = 1;
                }
                $arr[$i]["cat_name"] = self::getIndent($level, $end).$arr[$i]["cat_name"];
                array_push($list, $arr[$i]);
                self::setTreeList($arr, $arr[$i]["cat_id"]);
            }
        }
        $level--;
        return $list;
    }

    /*
      为递归函数服务 能够确定前面的符号
      查看父id为 $parent_id 的 结果有多少个
      $arr        匹配的数组
      $parent_id  匹配的父ID
      */
    public static function getNumById($arr, $parent_id)
    {
        $num = 0;
        foreach($arr as $k => $v){
            if($v["parent_id"] == $parent_id){
                $num++;
            }
        }
        return $num;
    }


    /*
为递归函数服务
返回缩进元素
$level  等级
$isEnd   是否到最后一个了，因为最后一个标识不一样
│       ├─      └─
*/
    private static function getIndent($level, $isEnd = 1)
    {
        $gap = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|";//前面的空隙
        if($level == 1){
            return "";
        }
        if($isEnd == 1){
            $res = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├─";
        }else{
            $res = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└─";
        }
        for($i=2; $i<$level; $i++){
            $res = $gap.$res;
        }
        return $res;
    }

}
